package com.example.factory;

import com.example.serialize.JobSerialize;
import com.example.serialize.impl.FastJSONJobSerialize;
import com.exmaple.dto.RpcResponse;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Logger;

public abstract class AbstractServerFactory implements SysServerFactory, InitializingBean, ApplicationListener<ContextRefreshedEvent>, DisposableBean {

    Logger logger = Logger.getLogger(getClass().getName());

    @Override
    public void afterPropertiesSet() throws Exception {
        this.init();
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {
            this.start();
        }
    }


    @Override
    public void destroy() throws Exception {
        this.stop();
    }

    @Override
    public JobSerialize getJobSerialize() {
        return new FastJSONJobSerialize();
    }

    @Override
    public RpcResponse handlerHTTP(String apiPath, Object obj) {
        RpcResponse rpcResponse = new RpcResponse();
        HttpURLConnection connection = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            URL url = new URL(apiPath);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestProperty("Content-Type", "application/json");
            outputStream = connection.getOutputStream();
            outputStream.write(getJobSerialize().decode(obj).getBytes());
            outputStream.flush();
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                rpcResponse.setSuccess(Boolean.TRUE);
                inputStream = connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                String responseBody = response.toString();
                if (!StringUtils.isEmpty(responseBody)) {
                    rpcResponse = (RpcResponse) getJobSerialize().encode(responseBody, RpcResponse.class);
                }
            }
        } catch (Exception e) {
            rpcResponse.setSuccess(Boolean.FALSE);
            rpcResponse.setErrInfo(e.getMessage());
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return rpcResponse;
    }
}
